<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        * {
            margin: 0;
            padding: 0;
        }

        div {
            position: absolute;
            height: 100px;
            width: 100px;
            background-color: #bfa;
        }
    </style>
    <script>
        window.onload = function () {

            let test = document.getElementById("test");
            let box = document.getElementById("box");

            /*             test.onkeydown = function (event) {
                            console.log(event.keyCode);
                            if (event.keyCode == 65)
                                console.log("按了Aa");
                        } */

            let dir = 0;
            let timer = setInterval(function () {
                let speed = 20;
                switch (dir) {
                    case 37:
                        {
                            box.style.left = box.offsetLeft - speed + "px";
                            console.log("left=" + box.style.left);
                            break;
                        }
                    case 38:
                        {
                            box.style.top = box.offsetTop - speed + "px";
                            console.log("top=" + box.style.top);
                            break;
                        }
                    case 39:
                        {
                            box.style.left = box.offsetLeft + speed + "px";
                            console.log("left=" + box.style.left);
                            break;
                        }
                    case 40:
                        {
                            box.style.top = box.offsetTop + speed + "px";
                            console.log("top=" + box.offsetTop);
                            break;
                        }
                }
            }, 30);

            document.onkeydown = function (event) {
                dir = event.keyCode;
            }
            document.onkeyup = function () {
                dir = 0;
            }
        }
    </script>
</head>

<body>
    <input type="text" id="test">
    <div id="box"></div>
</body>

</html>